package cn.jisol.ngame.demo.network.websocket.game.demo;


import cn.jisol.ngame.demo.client.picopark.PicoparkNClient;
import cn.jisol.ngame.demo.game.action.picopark.service.SNPicoparkAction;
import cn.jisol.ngame.demo.network.websocket.decoders.DefaultProtoBufDecoder;
import cn.jisol.ngame.demo.network.websocket.encoders.DefaultProtoBufEncoder;
import cn.jisol.ngame.proto.message.NGameMessageOuterClass;
import cn.jisol.ngame.util.spring.SpringBeanUtils;
import org.springframework.stereotype.Controller;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 友尽游戏的Demo
 */
@ServerEndpoint(
        value = "/game/cocos/demo/picopark/{uuid}",
        encoders = {DefaultProtoBufEncoder.class},
        decoders = {DefaultProtoBufDecoder.class}
)
@Controller
public class PicoparkGame {


    //客户端列表
    public static final Map<String, PicoparkNClient> CLIENTS = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session){

        String uuid = session.getPathParameters().get("uuid");

        //创建客户端对象
        PicoparkNClient client = null;

        SNPicoparkAction action = SpringBeanUtils.getBean(SNPicoparkAction.class);
        //第一个玩家加入进行初始化
        if (CLIENTS.values().size() <= 0){
            action.clients = CLIENTS;
        }

        if(Objects.isNull(CLIENTS.get(uuid))){
            client = new PicoparkNClient(uuid,session);
            System.out.println(String.format("%s 连接 Cocos 帧同步 WebSocket服务器成功",client.getUuid()));
            CLIENTS.put(uuid,client);
        }

        //判断游戏是否开始
        if(Objects.nonNull(action.room) && action.room.getIsStartGame()){

            //开始了则发送游戏信息
            assert client != null;
            client.getCnPicoparkAction().nGameRoomInfo(action.room);

        }

    }

    @OnMessage
    public void onMessage(Session session, NGameMessageOuterClass.NGameMessage message){

        String uuid = session.getPathParameters().get("uuid");

        //找到用户
        PicoparkNClient client = null;
        if(Objects.nonNull(client = CLIENTS.get(uuid))){
            //调用客户端消息统一接收
            client.onMessage(message);
        }

    }

    @OnClose
    public void onClose(Session session){

        String uuid = session.getPathParameters().get("uuid");
        PicoparkNClient client = CLIENTS.get(uuid);
        CLIENTS.remove(uuid);


        //如果没有玩家则关闭帧同步
        SNPicoparkAction action = SpringBeanUtils.getBean(SNPicoparkAction.class);
        //通知退出游戏
        action.nLeaveGame(client);
        if(CLIENTS.size() <= 0 && Objects.nonNull(action.nSyncFPSMode) && action.nSyncFPSMode.getIsExecute()) {
            action.nGameEnd();
        }

    }

    @OnError
    public void onError(Session session, Throwable t){

    }

}
